package com.itheima.reggie.handler;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.DeleteDishException;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

// 全局异常处理器
@ControllerAdvice //这是一个异常处理类
@ResponseBody //返回值为json,是一个控制层类
public class GlobalExceptionHandler {
	
	//处理唯一值重复的异常
	@ExceptionHandler(DuplicateKeyException.class)
	public ResultInfo handlerDuplicateKeyException(Exception e) {
		e.printStackTrace();
		if (e.getMessage().contains("idx_category_name")) {
			return ResultInfo.error("分类名称的值重复");
		}
		
		return ResultInfo.error("填写的值重复");
	}
	
	//处理自定义异常
	@ExceptionHandler(CustomException.class)
	public ResultInfo handlerCustomException(Exception e) {
		e.printStackTrace();
		
		return ResultInfo.error(e.getMessage());
	}
	
	//删除异常
	@ExceptionHandler(DeleteDishException.class)
	public ResultInfo handerDeleteException(Exception e) {
		e.printStackTrace();
		return ResultInfo.error(e.getMessage());
	}
	
	//处理非预期异常
	@ExceptionHandler(Exception.class)
	public ResultInfo handlerException(Exception e) {
		e.printStackTrace();
		// return ResultInfo.error(e.getMessage());
		return ResultInfo.error("服务器开小差了,正在杀Java程序员祭天");
	}
}
